<template>
  <div :class="{ fullscreen: fullscreen }" class="tinymce-container" :style="{ width: containerWidth }">
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <div class="editor-custom-btn-container">
      <editorImage
        color="#1890ff"
        class="editor-upload-btn"
        @successCBK="imageSuccessCBK"
      />
    </div>
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from './components/EditorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'
import { getToken } from '@/utils/auth'

// import '../../../public/tinymce/imagetools'  // 图片编辑增强

const defaultSettings = require('../../settings.js')

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN =
//   "https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js";

const tinymceCDN = window.location.origin + '/plugins/tinymce/tinymce.min.js'

export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function() {
        return (
          'vue-tinymce-' +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + '')
        )
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 860
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      resimg: '', // 上传img的url
      resVideo: '', // 上传视频的url
      uploaded: false, // 有没有上传完成
      languageTypeList: {
        en: 'en',
        zh: 'zh_CN',
        es: 'es_MX',
        ja: 'ja'
      }
    }
  },
  created() {
    console.log('123123')
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || '')
        )
      }
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
    },
    // images_upload_handler(blobInfo, success, failure, progress) {
    //       progress(0)
    //       const url = defaultSettings.uploadImgAll
    //       const formData = new FormData()
    //       formData.append('key', getToken())
    //       formData.append('file', blobInfo.blob())

    //       var xhr = new XMLHttpRequest()
    //       xhr.open('POST', url, true)
    //       xhr.send(formData)
    //       xhr.onload = () => {
    //         if (xhr.status === 200) {
    //           var res = JSON.parse(xhr.responseText)
    //           console.log(res)
    //           if (res.code === 200) {
    //             progress(100)
    //             success(res.datas.url)
    //           }
    //         }
    //       }
    //     },
    uploadImg(file, type) {
      const content = file
      const url = defaultSettings.uploadFileAll
      const formData = new FormData()
      formData.append('key', getToken())
      formData.append('file', content)
      return new Promise((ru, re) => {
        axios({
          method: 'post',
          // 服务器上传地址
          url: defaultSettings.uploadImg,
          data: formData,
          headers: {
            // 修改请求头
            'Content-Type': 'multipart/form-data',
            Authorization: getToken()

          }
        }).then(res => {
          if (res.status === 200) {
            if (type === 'image') {
              this.resimg = res.data.datas.src
            } else if (type === 'media') {
              this.resVideo = res.data.datas.src
            }
            this.uploaded = true
            ru()
          }
        })
          .catch(() => {
            re()
          })
      })
    },
    initTinymce() {
      var _this = this
      window.tinymce.init({
        // readonly:true,

        selector: `#${this.tinymceId}`,
        media_live_embeds:true,
        language: this.languageTypeList['zh'],
        // language_url:'http://tinymce.ax-z.cn/static/tiny/langs/zh_CN.js',
        language_url: '/tinymce/langs/zh_CN.js',

        height: this.height,
        body_class: 'panel-body ',
        object_resizing: true, // 图片放大缩小
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        content_style: `

*                         { padding:0; margin:0; }

html, body                { height:100%; }

img                       { max-width:100%; display:block;height:auto; }

a                         { text-decoration: none; }

iframe                    { width: 100%; }

p                         { line-height:1.6; margin: 0px; }

table                     { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }

.mce-object-iframe        { width:100%; box-sizing:border-box; margin:0; padding:0; }

ul,ol                     { list-style-position:inside; }

`
, // 初始化样式
        paste_data_images: true, // 设置为“true”将允许粘贴图像，而将其设置为“false”将不允许粘贴图像。
        plugin_preview_width : defaultSettings.isPhone?375:900, //This do the trick
        plugin_preview_height : defaultSettings.isPhone?1334:1080,
        file_picker_types: 'image media',
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'merge',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin

        init_instance_callback: (editor) => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
        // it will try to keep these URLs intact
        // https://www.tiny.cloud/docs-3x/reference/configuration/Configuration3x@convert_urls/
        // https://stackoverflow.com/questions/5196205/disable-tinymce-absolute-to-relative-url-conversions
        convert_urls: false,
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr("width");
        //     $image.removeAttr("height");
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr("data-wscntype", "image");
        //       $image.attr("data-wscnh", $image[0].height);
        //       $image.attr("data-wscnw", $image[0].width);
        //       $image.addClass("wscnph");
        //     }
        //   }, 0);
        //   return img;
        // },
        media_url_resolver: function(data, resolve) {
          try {
            let videoUri = encodeURI(data.url);
           let embedHtml = `<p>
                  <span
                    class="mce-object mce-object-video"
                    data-mce-selected="1"
                    data-mce-object="video"
                    data-mce-p-width="100%"
                    data-mce-p-height="auto"
                    data-mce-p-controls="controls"
                    data-mce-p-controlslist="nodownload"
                    data-mce-p-allowfullscreen="true"
                    data-mce-p-src=${videoUri} >
                    <video src=${data.url} width="100%" height="auto" controls="controls" controlslist="nodownload">
                    </video>
                  </span>
                </p>
                <p style="text-align: left;"></p>`;
            resolve({ html: embedHtml });
          } catch (e) {
            resolve({ html: "" });
          }
        },

        images_upload_handler(blobInfo, success, failure, progress) {
          progress(0)
          const url = defaultSettings.uploadImgAll
          const formData = new FormData()
          formData.append('key', getToken())
          formData.append('file', blobInfo.blob())

          var xhr = new XMLHttpRequest()
          xhr.open('POST', url, true)
          xhr.send(formData)
          xhr.onload = () => {
            if (xhr.status === 200) {
              var res = JSON.parse(xhr.responseText)
              console.log(res)
              if (res.code === 200) {
                progress(100)
                success(res.datas.url)
              }
            }
          }
        },
        file_picker_callback: function(callback, value, meta) {
          console.log('使用函数')
          if (meta.filetype == 'image') {
            console.log('判定为True')
            const input = document.createElement('input')// 创建一个隐藏的input
            input.setAttribute('type', 'file')
            // let that = this;
            input.onchange = function() {
              const file = this.files[0]// 选取第一个文件
              // console.log(file)
              _this.uploadImg(file, 'image').then(res => {
                console.log(_this.resimg, 1111)
                callback(_this.resimg) // 将url显示在弹框输入框中
              }) // 上传视频拿到url
            }
            // 触发点击
            input.click()
          }

          if (meta.filetype == 'media') {
            const input = document.createElement('input')// 创建一个隐藏的input
            input.setAttribute('type', 'file')
            // let that = this;
            input.onchange = function() {
              const file = this.files[0]// 选取第一个文件
              setTimeout(() => {
                console.log('定时器已经执行')
                console.log(_this)
                _this.uploadImg(file, 'media').then(res => {
                  console.log(_this.resVideo)
                  callback(_this.resVideo) // 将url显示在弹框输入框中
                }) // 上传视频拿到url
              }, 500)
            }
            // 触发点击
            input.click()
          }
        }

      })

      require('../../../public/tinymce/indent2em') // 首行二格
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      arr.forEach((v) => {
        console.log('数据', v)
        window.tinymce
          .get(this.tinymceId)
          .insertContent(`<img class="wscnph" src="${v.url}" >`)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}
</style>
